package com.algorithm.example.stack;

import java.util.Iterator;

/**
 * <p>
 * 链表栈
 * </p>
 *
 * @author lzt
 * @version 1.0
 * @since 2024/1/24 16:53
 */
public class LinkedListStack<E> implements Stack<E>, Iterable<E> {

    private int size;

    private int capacity;

    private Node<E> head = new Node<>(null, null);

    private static class Node<E> {
        private E value;
        private Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }

    }

    public LinkedListStack(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public boolean push(E value) {
        if (isFull()) {
            return false;
        }
        Node<E> next = head.next;
        head.next = new Node<>(value, next);
        size++;
        return true;
    }

    @Override
    public E pop() {
        if(isFull()) {
            return null;
        }
        Node<E> next = head.next;
        head.next = next.next;
        size--;
        return next.value;
    }

    @Override
    public E peek() {
        if(isFull()) {
            return null;
        }
        return head.next.value;
    }

    @Override
    public boolean isEmpty() {
        return head.next == null;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            Node<E> p = head;
            @Override
            public boolean hasNext() {
                return p.next != null;
            }

            @Override
            public E next() {
                Node<E> next = p.next;
                p = p.next;
                return next.value;
            }
        };
    }
}
